package com.hsogoo.avatar.processor;

import com.hsogoo.avatar.enums.AvatarResult;
import com.hsogoo.avatar.exceptions.AvatarException;
import com.hsogoo.avatar.executor.AvatarExecutor;
import com.hsogoo.avatar.executor.AvatarExecutors;
import com.hsogoo.avatar.executor.AvatarTask;
import com.hsogoo.avatar.executor.ExecutorFactory;
import com.hsogoo.avatar.model.AvatarRequest;
import com.hsogoo.avatar.model.AvatarResponse;
import com.hsogoo.avatar.model.ProviderMethod;
import com.hsogoo.avatar.registry.ProviderMethodRegistry;
import com.hsogoo.avatar.transport.AvatarChannel;
import com.hsogoo.avatar.transport.AvatarFuture;
import com.hsogoo.avatar.transport.AvatarProcessor;
import com.hsogoo.avatar.utils.ExceptionUtil;

import java.lang.reflect.Method;
import java.util.concurrent.Future;

import lombok.extern.slf4j.Slf4j;

/**
 * @Author huangsaigang
 * Created @2018/9/29.
 */
@Slf4j
public class DefaultAvatarProcessor implements AvatarProcessor {

    private AvatarExecutor executor;

    public DefaultAvatarProcessor(AvatarExecutor executor){
        this.executor = executor;
    }

    public DefaultAvatarProcessor(){
        executor = AvatarExecutors.providerExecutor();
    }

    @Override
    public void processRequest(AvatarChannel channel, AvatarRequest request) throws Exception {
        log.info("server got request={}", request);
        AvatarTask avatarTask = new AvatarTask(channel, request);
        if(executor == null){
            avatarTask.run();
        }else{
            executor.execute(avatarTask);
        }
    }

    @Override
    public void processResponse(AvatarResponse response) {
        log.info("client got response={}", response);
        AvatarFuture.setResponse(response);
    }

    @Override
    public void processException(AvatarChannel channel, AvatarRequest request, Throwable t) {
        AvatarResponse response = new AvatarResponse();
        response.setFailResult(AvatarResult.INVOKE_EXCEPTION, ExceptionUtil.getDetailMessage(t));
        channel.sendResponse(response);
    }
}
